package com.ptt.sqm.activity;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Map;

import org.ksoap2.serialization.PropertyInfo;

import android.app.Activity;
import android.app.FragmentManager;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ptt.sqm.component.MenuList;
import com.ptt.sqm.component.PagingScrollView;
import com.ptt.sqm.component.ScrollViewListener;
import com.ptt.sqm.model.AssessItem;
import com.ptt.sqm.model.AssessItemList;
import com.ptt.sqm.model.Login;
import com.ptt.sqm.model.PendingSummary;
import com.ptt.sqm.model.SearchAssess;
import com.ptt.sqm.model.SearchAssessCache;
import com.ptt.sqm.model.SearchAssessData;
import com.ptt.sqm.model.SearchAssessList;
import com.ptt.sqm.util.AppUtil;
import com.ptt.sqm.util.WidgetUtil;
import com.ptt.sqm.ws.AsyncResponse;
import com.ptt.sqm.ws.DefaultTask;
import com.ptt.sqmonmobile.R;

/**
 * A placeholder fragment containing a simple view.
 */
public class HomeAssessFragment extends DefaultFragment implements AsyncResponse {
	/**
	 * The fragment argument representing the section number for this fragment.
	 */
	private static final String ARG_SECTION_NUMBER = "section_number";

	private SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");

	// Create Webservice class object
	private DefaultTask mTask = null;

	private ArrayList<SearchAssessData> arrAssess;

	private SearchAssessList searchs;
	private SearchAssessCache searchCache;

	private AssessItemList assessItemList;

	private int currentPage;
	private int maxPage;
	private PendingSummary summary;

	private static HomeAssessFragment fragment;

	private View mProgressView;

	private View mContentView;
	
	private View mProgressSearchView;

	private View mContentSearchView;

	/**
	 * Returns a new instance of this fragment for the given section number.
	 * 
	 * @param projectId
	 */
	public static HomeAssessFragment newInstance(int sectionNumber, PendingSummary summary) {
		fragment = new HomeAssessFragment(summary);
		Bundle args = new Bundle();
		args.putInt(ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);

		return fragment;
	}

	public HomeAssessFragment(PendingSummary summary) {
		this.summary = summary;
	}

	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		// Loading...
		mProgressView = view.findViewById(R.id.progress);
		mContentView = view.findViewById(R.id.container);		
		mProgressSearchView = view.findViewById(R.id.search_listview_progress);
		mContentSearchView = view.findViewById(R.id.search_listview);

		Login login = session.getUserDetails();
		searchCache = new SearchAssessCache();
		currentPage = 0;

		// set Header
		TextView fullnameAssess = (TextView) view.findViewById(R.id.fullname_assess);
		TextView groupAssess = (TextView) view.findViewById(R.id.group_assess);
		TextView year = (TextView) view.findViewById(R.id.year_assess);
		TextView project = (TextView) view.findViewById(R.id.project_assess);
		TextView sumPending = (TextView) view.findViewById(R.id.sum_pending);
		TextView sumDraft = (TextView) view.findViewById(R.id.sum_draft);
		TextView sumSubmit = (TextView) view.findViewById(R.id.sum_submit);
		TextView sumTotal = (TextView) view.findViewById(R.id.sum_status);

		fullnameAssess.setText(login.User_Name);
		groupAssess.setText(login.User_Group_Name);
		year.setText(summary.YearName);
		project.setText(summary.ProjectName);
		sumPending.setText(String.valueOf(summary.Pending));
		sumDraft.setText(String.valueOf(summary.Draft));
		sumSubmit.setText(String.valueOf(summary.Submit));
		sumTotal.setText(String.valueOf(summary.Total));

		WidgetUtil.showProgress(mContentSearchView, mProgressSearchView, true);
		
		PropertyInfo projProp = new PropertyInfo();
		PropertyInfo pageSize = new PropertyInfo();
		PropertyInfo pageNumber = new PropertyInfo();

		projProp.setName("ProjectId");
		projProp.setValue(summary.ProjectId);
		projProp.setType(String.class);

		pageSize.setName("Page_Size");
		pageSize.setValue(getString(R.string.page_size));
		pageSize.setType(Integer.class);

		pageNumber.setName("Page_Number");
		pageNumber.setValue(AppUtil.FIRST_PAGE);
		pageNumber.setType(Integer.class);

		searchCache.ProjectID = projProp;
		searchCache.PageSize = pageSize.getValue().toString();
		searchCache.PageNumber = pageNumber.getValue().toString();

		mTask = new DefaultTask(com, getString(R.string.method_searchpending));
		mTask.delegate = fragment;
		mTask.execute(projProp, pageSize, pageNumber);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.home_assess, container, false);
		return rootView;
	}

	private class adtSearchMultipleLine extends BaseAdapter {
		private class ListViewCustomItem {
			public ImageView status;
			public TextView data1;
			public TextView data2;
			public TextView data3;
			public TextView data4;
			public TextView data5;
			public TextView data6;
			public TextView data7;
			public TextView data8;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return arrAssess.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int arg0, View arg1, ViewGroup arg2) {
			// TODO Auto-generated method stub
			arg1 = LayoutInflater.from(HomeAssessFragment.this.getActivity()).inflate(R.layout.search_listitem, null);

			ListViewCustomItem lsvItem = new ListViewCustomItem();
			lsvItem.status = (ImageView) arg1.findViewById(R.id.status);
			lsvItem.data1 = (TextView) arg1.findViewById(R.id.data1);
			lsvItem.data2 = (TextView) arg1.findViewById(R.id.data2);
			lsvItem.data3 = (TextView) arg1.findViewById(R.id.data3);
			lsvItem.data4 = (TextView) arg1.findViewById(R.id.data4);
			lsvItem.data5 = (TextView) arg1.findViewById(R.id.data5);
			lsvItem.data6 = (TextView) arg1.findViewById(R.id.data6);
			lsvItem.data7 = (TextView) arg1.findViewById(R.id.data7);
			lsvItem.data8 = (TextView) arg1.findViewById(R.id.data8);

			if (arrAssess.get(arg0).getStatus() != null) {
				if (arrAssess.get(arg0).getStatus().equals(AppUtil.ASSESS_STATUS_DRAFT)) {
					lsvItem.status.setImageResource(R.drawable.status_assess_draft);
				} else if (arrAssess.get(arg0).getStatus().equals(AppUtil.ASSESS_STATUS_SUBMIT)) {
					lsvItem.status.setImageResource(R.drawable.status_assess_submit);
				} else if (arrAssess.get(arg0).getStatus().equals(AppUtil.ASSESS_STATUS_NONE)) {
					lsvItem.status.setImageResource(R.drawable.status_assess_none);
				}
			} else {
				lsvItem.status.setImageResource(R.drawable.status_assess_none);
			}

			if (arrAssess.get(arg0).getData1() != null) {
				lsvItem.data1.setText(arrAssess.get(arg0).getData1());
			}

			if (arrAssess.get(arg0).getData2() != null) {
				lsvItem.data2.setText(arrAssess.get(arg0).getData2());
			}

			if (arrAssess.get(arg0).getData3() != null) {
				lsvItem.data3.setText(arrAssess.get(arg0).getData3());
			}

			if (arrAssess.get(arg0).getData4() != null) {
				lsvItem.data4.setText(arrAssess.get(arg0).getData4());
			}

			if (arrAssess.get(arg0).getData5() != null) {
				lsvItem.data5.setText(arrAssess.get(arg0).getData5());
			}

			if (arrAssess.get(arg0).getData6() != null) {
				lsvItem.data6.setText(arrAssess.get(arg0).getData6());
			}

			if (arrAssess.get(arg0).getData7() != null) {
				lsvItem.data7.setText(arrAssess.get(arg0).getData7());
			}

			if (arrAssess.get(arg0).getData8() != null) {
				lsvItem.data8.setText(arrAssess.get(arg0).getData8());
			}

			// Go to MakeAssess
			arg1.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View view) {
					if (WidgetUtil.isLocationServiceAvailable(getActivity())) {
						assessItemList = new AssessItemList();
						assessItemList.stationId = arrAssess.get(arg0).getStationId();
						assessItemList.stationName = arrAssess.get(arg0).getStationName();
						assessItemList.locationId = arrAssess.get(arg0).getLocationId();
						assessItemList.projectId = arrAssess.get(arg0).getProjectId();
						assessItemList.projectName = arrAssess.get(arg0).getProjectName();
						assessItemList.cycleAssessId = arrAssess.get(arg0).getCycleAssessId();
						assessItemList.cycle = arrAssess.get(arg0).getCycle();
						assessItemList.yearAssessId = arrAssess.get(arg0).getYearAssessId();
						assessItemList.assessDataId = arrAssess.get(arg0).getAssessDataId();

						getAssessItemService(arrAssess.get(arg0).getProjectId(), arrAssess.get(arg0).getCycleAssessId());
					}
				}
			});
			return arg1;
		}

		@Override
		public void unregisterDataSetObserver(DataSetObserver observer) {
			if (observer != null) {
				super.unregisterDataSetObserver(observer);
			}
		}
	}

	@Override
	public void processFinish(String method, Object output) {
		// TODO Auto-generated method stub
		// Toast.makeText(getActivity(), (String) output,
		// Toast.LENGTH_LONG).show();
		try {
			if (method.equals(getString(R.string.method_searchpending)))
				getPending(method, output);
			else if (method.equals(getString(R.string.method_listassessitem)))
				getListAssessItem(method, output);
		} catch (Exception e) {
		}
	}

	private void getListAssessItem(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			String tempStationId = assessItemList.stationId;
			String tempStationName = assessItemList.stationName;
			String tempProjId = assessItemList.projectId;
			String tempProjName = assessItemList.projectName;
			String tempCycleId = assessItemList.cycleAssessId;
			String tempCycle = assessItemList.cycle;
			String tempYearId = assessItemList.yearAssessId;
			String tempLocationId = assessItemList.locationId;
			String tempAssessDataId = assessItemList.assessDataId;

			assessItemList = (AssessItemList) gson.fromJson((String) output, AssessItemList.class);

			assessItemList.stationId = tempStationId;
			assessItemList.stationName = tempStationName;
			assessItemList.locationId = tempLocationId;
			assessItemList.projectId = tempProjId;
			assessItemList.projectName = tempProjName;
			assessItemList.cycleAssessId = tempCycleId;
			assessItemList.cycle = tempCycle;
			assessItemList.yearAssessId = tempYearId;
			assessItemList.assessDataId = tempAssessDataId;

			Log.i("projectId", assessItemList.projectId);
			Log.i("cycleAssessId", assessItemList.cycleAssessId);
			Log.i("stationId", assessItemList.stationId);
			Log.i("assessDataId", assessItemList.assessDataId);

			FragmentManager fragmentManager = getFragmentManager();
			fragmentManager.beginTransaction().addToBackStack(AppUtil.STACK_HOME_ASSESS)
				.replace(R.id.container, MakeAssessFragment.newInstance(menuList.getPosFrm_AssessData(), assessItemList, false)).commit();

		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
			WidgetUtil.showProgress(mContentView, mProgressView, false);			
		}
		
	}

	private void getPending(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			searchs = (SearchAssessList) gson.fromJson((String) output, SearchAssessList.class);

			arrAssess = new ArrayList<SearchAssessData>();
			SearchAssessData assess;
			for (SearchAssess search : searchs.SearchAssess) {
				assess = new SearchAssessData();
				assess.setStatus(search.Assess_Status);
				assess.setData1(search.StationId + "  " + search.StationName);
				assess.setData2(search.Projectname);
				assess.setData3(search.Cycle);
				assess.setData4(search.UserName);
				assess.setData5(search.Assessdate != null ? search.Assessdate : "");
				assess.setData6(search.UserTypeName);
				assess.setData7(search.TotalPoint != null ? search.TotalPoint + "  " + getString(R.string.point) : AppUtil.EMPTY);
				assess.setData8(search.UserTypeName);
				assess.setProjectId(search.projectid);
				assess.setProjectName(search.Projectname);
				assess.setCycleAssessId(search.CycleAssessId);
				assess.setCycle(search.Cycle);
				assess.setStationId(search.StationId);
				assess.setStationName(search.StationName);
				assess.setLocationId(search.LOCATION_ID);
				assess.setYearAssessId(search.YearId);
				assess.setAssessDataId(search.AssessDataId != null ? search.AssessDataId : AppUtil.EMPTY);
				arrAssess.add(assess);
			}

			ListView listSearch = (ListView) getView().findViewById(R.id.search_listview);
			adtSearchMultipleLine adt = new adtSearchMultipleLine();
			listSearch.setAdapter(adt);

			// calculate begin - end
			int endNo = Integer.parseInt(searchCache.PageNumber) * Integer.parseInt(searchCache.PageSize);
			int beginNo = (endNo - Integer.parseInt(searchCache.PageSize)) + 1;
			if (endNo >= searchs.SearchAssess.get(0).Row_Count)
				endNo = searchs.SearchAssess.get(0).Row_Count;

			// set outstanding assess
			TextView outstanding = (TextView) getView().findViewById(R.id.outstanding_assess);
			String outstandingStr = getString(R.string.outstanding_assess);
			outstandingStr = outstandingStr.replaceAll("@0", String.valueOf(beginNo));
			outstandingStr = outstandingStr.replaceAll("@1", String.valueOf(endNo));
			outstandingStr = outstandingStr.replaceAll("@2", String.valueOf(searchs.SearchAssess.get(0).Row_Count));
			outstanding.setText(outstandingStr);

			if (currentPage == 0) {
				double doubleCount = (double) searchs.SearchAssess.get(0).Row_Count / Integer.parseInt(searchCache.PageSize);
				final int pageCount = (int) Math.ceil(doubleCount);

				for (int i = 1; i <= pageCount; i++) {
					final int noOfPage;

					noOfPage = i;
					final LinearLayout mLinearScroll = (LinearLayout) getView().findViewById(R.id.paging);
					TextView page = new TextView(getActivity());

					LayoutParams lp = new LinearLayout.LayoutParams(50, 50);

					page.setTextColor(Color.WHITE);
					page.setText(String.valueOf(i));
					page.setGravity(Gravity.CENTER);
					page.setBackground(getResources().getDrawable(R.drawable.page_indicator));
					mLinearScroll.addView(page, lp);
					mLinearScroll.setBackgroundColor(getResources().getColor(R.color.search_bar));
					if (noOfPage == 1)
						page.setSelected(true);
					page.setOnClickListener(new OnClickListener() {

						@Override
						public void onClick(View v) {

							// Page Selected Hilight
							for (int index = 0; index < mLinearScroll.getChildCount(); index++) {
								mLinearScroll.getChildAt(index).setSelected(false);
							}
							v.setSelected(true);

							if (noOfPage != currentPage) {
								currentPage = noOfPage;
								getPaging(Integer.parseInt(getString(R.string.page_size)), noOfPage);
							}
						}

					});
				}

				// init paging				
				final PagingScrollView mScroll = (PagingScrollView) getView().findViewById(R.id.paging_scroll);

				ViewTreeObserver vto = mScroll.getViewTreeObserver();
				vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

					@Override
					public void onGlobalLayout() {
						// TODO Auto-generated method stub
						maxPage = mScroll.getChildAt(0).getMeasuredWidth() - mScroll.getMeasuredWidth();
						mScroll.getViewTreeObserver().removeGlobalOnLayoutListener(this);
					}
				});

				mScroll.setScrollViewListener(new ScrollViewListener() {

					@Override
					public void onScrollChanged(PagingScrollView scrollView, int x, int y, int oldx, int oldy) {
						// TODO Auto-generated method stub
						if (maxPage > 0) {
							ImageView mPrevious = (ImageView) getView().findViewById(R.id.previous_page);
							ImageView mNext = (ImageView) getView().findViewById(R.id.next_page);
							int max = scrollView.getChildAt(0).getMeasuredWidth() - scrollView.getMeasuredWidth();
							if (x <= 0) {
								mPrevious.setVisibility(ImageView.INVISIBLE);
								mNext.setVisibility(ImageView.VISIBLE);
							} else if (x >= max) {
								mPrevious.setVisibility(ImageView.VISIBLE);
								mNext.setVisibility(ImageView.INVISIBLE);
							} else {
								mPrevious.setVisibility(ImageView.VISIBLE);
								mNext.setVisibility(ImageView.VISIBLE);
							}
						}
					}
				});
				
				ImageView mPrevious = (ImageView) getView().findViewById(R.id.previous_page);
				ImageView mNext = (ImageView) getView().findViewById(R.id.next_page);

				if (pageCount > Integer.parseInt(getString(R.string.paging_size))) {
					mPrevious.setVisibility(ImageView.INVISIBLE);
					mNext.setVisibility(ImageView.VISIBLE);
				} else {
					mPrevious.setVisibility(ImageView.INVISIBLE);
					mNext.setVisibility(ImageView.INVISIBLE);
				}


			}

			Log.i(method, "Call WS Success");

		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
			Toast.makeText(getActivity().getApplicationContext(), getString(R.string.alert_no_data), Toast.LENGTH_LONG).show();
		}

		WidgetUtil.showProgress(mContentSearchView, mProgressSearchView, false);
	}

	public void getPaging(int size, int number) {
		WidgetUtil.showProgress(mContentSearchView, mProgressSearchView, true);
		
		PropertyInfo pageSize = new PropertyInfo();
		PropertyInfo pageNumber = new PropertyInfo();

		pageSize.setName("Page_Size");
		pageSize.setValue(String.valueOf(size));
		pageSize.setType(Integer.class);

		pageNumber.setName("Page_Number");
		pageNumber.setValue(String.valueOf(number));
		pageNumber.setType(Integer.class);

		searchCache.PageSize = String.valueOf(size);
		searchCache.PageNumber = String.valueOf(number);

		mTask = new DefaultTask(com, getString(R.string.method_searchpending));
		mTask.delegate = fragment;
		mTask.execute(searchCache.ProjectID, pageSize, pageNumber);

	}

	protected void getAssessItemService(String project, String cycle) {
		// TODO Auto-generated method stub
		WidgetUtil.showProgress(mContentView, mProgressView, true);
		PropertyInfo projProp = new PropertyInfo();
		projProp.setName(AssessItem.ProjectId);
		projProp.setValue(project);
		projProp.setType(String.class);

		PropertyInfo cycleProp = new PropertyInfo();
		cycleProp.setName(AssessItem.Cycle);
		cycleProp.setValue(cycle);
		cycleProp.setType(String.class);

		mTask = new DefaultTask(com, getString(R.string.method_listassessitem));
		mTask.delegate = this;
		mTask.execute(projProp, cycleProp);

	}

	@Override
	public void processFinish(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub

	}
}
